package com.lqq.school.shiro;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lqq.school.mapper.UserMapper;
import com.lqq.school.domain.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserRealm extends AuthorizingRealm {

    @Resource
    private UserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("---------------执行了授权doGetAuthorizationInfo");
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        Subject subject= SecurityUtils.getSubject();

        //拿到当前用户登陆对象
        User currentUser= (User) subject.getPrincipal();//拿到User对象
        if (currentUser.getRoles().equals("admin")) {
            info.addRole("admin");
            return info;
        }
        System.out.println("---------------执行了授权doGetAuthorizationInfo");
        info.addRole("common");//设置当前用户对象

        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("---------------执行了认证doGetAuthenticationInfo");

        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        //查询数据库是否存在改用户
       // Map<String, Object> map = new HashMap<String, Object>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //map.put("username", userToken.getUsername());
        queryWrapper.eq("username",userToken.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        //User user = userMapper.queryByUsername(userToken.getUsername());

        if (user == null) {
            return null;//抛出异常，没有该用户
        }

        //String username = user.getUsername();
        String password = user.getPassword();
        //从数据库获取账户密码
        //System.out.println("=-------------认证");


        return new SimpleAuthenticationInfo(user, password, "");
    }
}
